import base64
import json
import time
import os
import cv2
import numpy as np


def jpg2bs64(file, cameraNo, time,type,needTag,output_path):
    f = open(file, 'rb')
    bs64_bytes = base64.b64encode(f.read())
    bs64_str = bs64_bytes.decode('utf-8')
    f.close()
    res = {}
    res['cameraNo'] = cameraNo
    res['time'] = time
    res['type'] = type
    res['srcImg'] = bs64_str
    res['needTag'] = needTag
    
    with open(output_path, 'w') as f:
        json.dump(res, f, indent=4)
    f.close()
    
def json2res(info):
    """[summary]

    Args:
        file (str): the path of input json file

    Returns:
        dict: dict of image's information 
    """

    picture_string = info['srcImg']
    picture = base64.b64decode(picture_string)
    imag = cv2.imdecode(np.array(bytearray(picture), dtype='uint8'), cv2.IMREAD_UNCHANGED)
    
    cameraNo = info['cameraNo']
    time = info['time']
    type = info['type']
    needTag = info['needTag']
    return imag, cameraNo, time, type, needTag

def array2bs64str(array):
    """[summary]

    Args:
        array (np.array): array formated picture

    Returns:
        bs64_str: [description]
    """
    img_encode = cv2.imencode('.jpg',array)[1]
    data_image = np.array(img_encode)
    bytes_image = data_image.tobytes()
    bs64_image = base64.b64encode(bytes_image)
    bs64str_image = bs64_image.decode('utf-8')
    return bs64str_image

def test(file, output_path):
    """[summary]

    Args:
        file (str): the path of json file
        output_path (.jpg) the ouputpath of jpg file
    """
    with open(file, 'r') as f:
        res = json.load(f)
    f.close()
    bs64str_image= res['tagImg']
    bytes_image = base64.b64decode(bs64str_image)
    
    with open(output_path, 'wb') as f:
        f.write(bytes_image)
    f.close()
    
if __name__ == '__main__':
    # jpg2bs64(r'input_json\climb2_201o.jpg', cameraNo='C01',type='follow',time= '2021-11-12 12:13:54',needTag='1', output_path='input_json/res.json') 
    # jpg2bs64(r'input_json\3FJ33-1.jpg', cameraNo='C01',type='phone',time='2021-11-12 12:13:56', needTag='1', output_path='input_json/test2.json') 
    # jpg2bs64(r'input_json\3FJ33-12.jpg', cameraNo='C01',type='phone',time='2021-11-12 12:13:54', needTag='1', output_path='input_json/test3.json')     
    test('output_json/res.json','output_json/res.jpg')
    pass
    
    